package com.wthink.hzgj.util

import com.wthink.card.ShdThread
import java.nio.ByteBuffer

internal fun update_CRC(
    data: ByteArray?,
    length: ByteArray,
    type: Int,
    devicetype: Int,
    len: Int
) // 校验位 异或校验
        : Int {
    var checksum = 0
    checksum = checksum xor length[0].toInt()
    checksum = checksum xor length[1].toInt()
    checksum = checksum xor devicetype
    checksum = checksum xor type
    if (data != null) {
        for (i in 0 until len) {
            checksum = checksum xor data[i].toInt()
        }
    }
    return checksum and 0xff
}

fun packBoardNormalClient(
    type: Int, data: ByteArray?, datalen: Int,
    out: ByteBuffer, devicetype: Int
): Int {
    out.put(0x7E.toByte())
    out.put(intToByte(datalen + 5))//数据长度
    out.put(devicetype.toByte())            //设备类型
    out.put(intToByte(type))
    if (datalen > 0 && data != null) {
        out.put(data, 0, datalen)
    }
    out.put(update_CRC(data, intToByte(datalen + 5), type, devicetype, datalen).toByte())
    out.put(0x7F.toByte())
    return out.position()
}

fun packMainBoardNormalFrm(
    type: Int,
    data: ByteArray?,
    datalen: Int,
    out: ByteBuffer
): Int {
    if (datalen + ShdThread.BUNDLE_HEARDER_LEN + ShdThread.BUNDLE_TAIL_LEN > ShdThread.MAX_BUNDLE_LEN) {
        return ShdThread.ER_SEND_FAILE
    }
    out.put(0x24.toByte())
    out.put(type.toByte())
    out.put((datalen + ShdThread.BUNDLE_TAIL_LEN) as Byte)
    if (datalen > 0 && data != null) {
        out.put(data, 0, datalen)
    }
    out.put(0x00.toByte())
    out.put(0xff.toByte())
    return out.position()
}


fun intToByte(i: Int): ByteArray { // int转byte 高前，低后
    val abyte0 = ByteArray(2)
    abyte0[0] = (0xff and (i shr 8)).toByte()
    abyte0[1] = (0xff and i).toByte()
    return abyte0
}

fun SendToMainBoardNormalFrm(type: Int, data: ByteArray, datalen: Int, drivceType: Int): ByteArray {
    val out = ByteBuffer.allocate(10 + datalen)
    packBoardNormalClient(type, data, datalen, out, drivceType)
    val content = ByteArray(out.position())
    out.flip()
    out.get(content)
    return content
}


